package com.gantzgulch.generics;

import static com.gantzgulch.generics.Cast.cast;

import java.lang.reflect.Array;

public class Factory<T> {

	public static <U> Factory<U> create(Class<U > myClass){
		return new Factory<U>(myClass);
	}
	
	private Class<T> myClass;
	
	public Factory(Class<T> myClass){
		this.myClass = myClass;
	}
	
    public T createObject(){
        try {
            return myClass.newInstance();
        } catch (Exception e) {
        	throw Objects.ensureRuntimeException(e);
        }
    }

    public T[] createArray(int length){
        return cast(Array.newInstance(myClass, length));
    }
    
    public T[] createArrayWithDefaults(int length){
        
        T[] array = createArray(length);

        for(int i=0; i<array.length; i++){
        	array[i] = createObject();
        }
        
        return array;
    }
}
